package com.czxy.controller;

import com.alibaba.fastjson.JSON;
import com.czxy.pojo.Category;
import com.czxy.service.CategoryService;
import com.czxy.vo.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张青卯
 */
@RestController
@RequestMapping
public class CategoryController {

    private final CategoryService categoryService;

    private final RedisTemplate<String,String> redisTemplate;

    @Autowired
    public CategoryController(CategoryService categoryService, RedisTemplate<String, String> redisTemplate) {
        this.categoryService = categoryService;
        this.redisTemplate = redisTemplate;
    }


    @GetMapping("/categorys")
    public ResponseEntity<Object> categorys(){
        String categorys = redisTemplate.opsForValue().get("categorys");
        if(categorys!=null){
            return ResponseEntity.ok(categorys);
        }
        List<Category> category = categoryService.categorys();
        List<Category> list1 = findCategoryByParentId(0, category);
        for(Category c1:list1){
            List<Category> list2 = findCategoryByParentId(c1.getId(), category);
            c1.setChildren(list2);
            for(Category c2:list2){
                List<Category> list3 = findCategoryByParentId(c2.getId(), category);
                c2.setChildren(list3);
            }
        }
        BaseResult result = new BaseResult(0,"成功",list1);
        redisTemplate.opsForValue().set("categorys",JSON.toJSONString(result));
        return ResponseEntity.ok(result);
    }

    /**
     * findCategoryByParentId 用于查找三级分类
     * @param parentid 父ID
     * @param list 分类集合
     * @return List<Category>
     */
    private List<Category> findCategoryByParentId(Integer parentid, List<Category> list){
        List<Category> children = new ArrayList<>();
        for (Category c : list) {
            if(c.getParentId()!=null&&c.getParentId().equals(parentid)){
                children.add(c);
            }
        }
        return children;
    }
}
